package com.zut.Service.loginService.loginServiceImpl;


import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zut.Annotations.MyLogs;
import com.zut.Dao.UserInfoDao;
import com.zut.Pojo.UserInfo;
import com.zut.Service.loginService.LoginService;
import com.zut.Util.RedisUtil;
import com.zut.Util.SendSMS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: 无恙
 * @Description: 登录服务
 * @DateTime: 2023.10.24
 */

@Service("com.zut.Service.loginService")
public class loginServiceImpl implements LoginService {
    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    @MyLogs
    public Map<String,UserInfo> loginByPsw(String phone, String psw) {
        //结果
        Map<String,UserInfo> result=new HashMap<>();
        //MD5加密
        String PswByMD5=SecureUtil.md5(psw);

        //调取数据库
        UserInfo userInfo = userInfoDao.selectOne(
                new QueryWrapper<>(UserInfo.builder()
                        .phone(phone).password(PswByMD5).build()));
        //生成UUID
        String UUID= IdUtil.randomUUID();
        //存入到缓存区
        redisUtil.set(UUID,userInfo, 100L);
        //对密码脱敏处理，
        userInfo.setPassword("*********");
        result.put(UUID,userInfo);
        return result;
    }

    /**
     * @param UUID
     * @param code
     * @return UseInfo
     */
    @Override
    @MyLogs
    public UserInfo loginByCode(String UUID, String phone, String code) {
        //从redis获取缓存UUID code
        Object codeRedis = redisUtil.get(UUID);
        //判断验证码是否存在或验证码是否正确
        if(Objects.isNull(codeRedis) || !codeRedis.equals(code)){
            return null;
        }

        UserInfo info = UserInfo.builder().phone(phone).build();
        //验证码正确,从数据库获取个人信息
        UserInfo userInfo = userInfoDao.selectOne(new QueryWrapper<>(info));
        if(!Objects.isNull(userInfo)){
            return userInfo;
        }else {
            //像数据库插入个人信息
            userInfoDao.insert(info);
            return info;
        }

    }

    /**
     * TODO  前后手机号不一致，解决：前端处理
     *@Description:获取验证码
     * @param phone
     * @return
     */

    @Override
    @MyLogs
    public String GetCode(String phone) {
        String result=null;
        //获取验证码
        Map<String, Object> map = SendSMS.sendSMS(phone);
        //生成UUID
        String UUID= IdUtil.randomUUID();
        //存入到缓存区
        boolean code = redisUtil.set(UUID, map.get("code"), 100L);
        if(code){
           result=UUID;
        }
        return result;
    }
}
